package com.nexen.web.controller.wechat;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.nexen.common.annotation.Anonymous;
import com.nexen.common.config.wechat.WxMaConfiguration;
import com.nexen.common.core.controller.BaseController;
import com.nexen.common.core.domain.AjaxResult;
import com.nexen.common.utils.StringUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>Title: WxLoginController</p>
 * <p>Description: </p>
 *
 * @author cong.zhang
 * @version 1.0.0
 * @date 2024/8/4
 * @time 14:59
 */
@RestController
@RequestMapping("/wexin")
public class WxLoginController extends BaseController {

    /**
     *
     * @param dto
     * @return
     */
    @Anonymous
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginDTO dto) {
        String appid = (String) dto.getAppid();
        String code = (String) dto.getCode();

        if (StringUtils.isEmpty(appid) || StringUtils.isEmpty(code)) {
            return AjaxResult.error("参数异常");
        }
        // 获取服务
        WxMaService service = WxMaConfiguration.getService(appid);
        WxMaJscode2SessionResult session = null;
        try {
            // 获取登录信息
            session = service.getUserService().getSessionInfo(code);
        } catch (WxErrorException e) {
            throw new RuntimeException("登录异常");
        }
        String openid = session.getOpenid();
        String sessionKey = session.getSessionKey();
        String unionid = session.getUnionid();
        // 查询数据库信息
//        UserOauth oauth = userOauthMapper.selectOne(new LambdaQueryWrapper<UserOauth>().eq(UserOauth::getValidStatus, 1)
//                .eq(UserOauth::getLoginType, dto.getTyper()).eq(UserOauth::getOpenid, openid).last("limit 1"));
//        if (oauth == null) {
//            // 插入用户信息
//            UserInfo user = new UserInfo();
//            user.setUserId(IdUtil.getSnowflakeNextIdStr());// 主键
//            user.setUsername("默认昵称_"+IdUtil.getSnowflakeNextIdStr());
//            user.setNickName("默认昵称_"+IdUtil.getSnowflakeNextIdStr());
//            userInfoMapper.insert(user) ;
//            // 插入授权信息
//            oauth = new UserOauth();
//            oauth.setId(IdUtil.getSnowflakeNextIdStr());
//            oauth.setUserId(user.getUserId());
//            oauth.setLoginType(dto.getTyper());
//            oauth.setOpenid(openid);
//            oauth.setValidStatus(1);
//            // 插入数据库
//            userOauthMapper.insert(oauth);
//        }
//        // token登录
//        StpUtil.login(oauth.getUserId());
//        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        Map<String,Object> ret = new HashMap<>();
//        ret.put("tokenInfo" , tokenInfo) ;
        ret.put("openid" , openid) ;
        ret.put("sessionKey" , sessionKey) ;
        ret.put("unionid" , unionid) ;

        return AjaxResult.success(ret);
    }

    /**
     *
     * @param dto
     * @return
     */
    @Anonymous
    @PostMapping("/getPhoneNumber")
    public AjaxResult getPhoneNumber(@RequestBody LoginDTO dto) {
        String appid = (String) dto.getAppid();
        String code = (String) dto.getCode();

        if (StringUtils.isEmpty(appid) || StringUtils.isEmpty(code)) {
            return AjaxResult.error("参数异常");
        }
        // 获取服务
        WxMaService service = WxMaConfiguration.getService(appid);
        WxMaJscode2SessionResult session = null;
        try {
            // 获取登录信息
            session = service.getUserService().getSessionInfo(code);
        } catch (WxErrorException e) {
            throw new RuntimeException("登录异常");
        }
        String openid = session.getOpenid();
        Map<String,Object> ret = new HashMap<>();
//        ret.put("tokenInfo" , tokenInfo) ;
        ret.put("openid" , openid) ;

        return AjaxResult.success(ret);
    }

    /**
     *
     * @param dto
     * @return
     */
    @Anonymous
    @PostMapping("/getUserInfo")
    public AjaxResult getUserInfo(@RequestBody LoginDTO dto) {
        String appid = dto.getAppid();
        String sessionKey = dto.getSessionKey();
        String encryptedData = dto.getEncryptedData();
        String ivStr = dto.getIvStr();

        if (StringUtils.isEmpty(sessionKey) || StringUtils.isEmpty(encryptedData)|| StringUtils.isEmpty(ivStr)) {
            return AjaxResult.error("参数异常");
        }
        // 获取服务
        WxMaService service = WxMaConfiguration.getService(appid);
        WxMaUserInfo session = null;
        try {
            // 获取登录信息
            session = service.getUserService().getUserInfo(sessionKey, encryptedData, ivStr);
        } catch (Exception e) {
            throw new RuntimeException("获取用信息异常");
        }

        return AjaxResult.success(session);
    }

}
